package com.weijie.relaxed.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.weijie.relaxed.R;
import com.weijie.relaxed.views.InputView;

/** 
 * 登录
 * @author weijie 
 * @version 创建时间：2015年3月18日 下午4:05:41 
 */
public class LoginActivity extends Activity implements OnClickListener {

	private InputView username,password;
	private String name,pw;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		username = (InputView) findViewById(R.id.username);
		password = (InputView) findViewById(R.id.password);
		findViewById(R.id.register).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.register:
			startActivity(new Intent(this,RegisterActivity.class));
			break;
		case R.id.login:
			//startActivity(new Intent(this,MainActivity.class));
			if(username.getText().trim().equals("")) {
				Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
				return;
			}
			if(password.getText().trim().equals("")) {
				Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
				return;
			}

			name = username.getText().trim();
			pw = password.getText().trim();

			EMChatManager.getInstance().login(name,pw,
					new EMCallBack() {//回调
				@Override
				public void onSuccess() {
					runOnUiThread(new Runnable() {
						public void run() {
							//Log.d("main", "登陆聊天服务器成功！");	

							Message mes = new Message();
							mes.what = 2;
							handler.sendMessage(mes);
						}
					});
				}

				@Override
				public void onProgress(int progress, String status) {

				}

				@Override
				public void onError(int code, String message) {
					//Log.d("main", "登陆聊天服务器失败！");
					//Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
					Message mes = new Message();
					mes.obj = message;
					mes.what = 1;
					handler.sendMessage(mes);
				}
			});
			break;

		default:
			break;
		}
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Toast.makeText(LoginActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				super.handleMessage(msg);
				break;
			case 2:
				Editor edit = getSharedPreferences("user", Context.MODE_PRIVATE).edit();
				edit.putString("username", name);
				edit.putString("password", pw);
				edit.commit();
				
				startActivity(new Intent(LoginActivity.this,MainActivity.class));
				LoginActivity.this.finish();
				break;

			default:

				break;
			}
		}

	};

}
